import QtQuick 1.1
//import com.nokia.symbian 1.0
import com.nokia.meego 1.0
import com.nokia.extras 1.0
import "Viewer.js" as JS
import "Common.js" as COM
import REngine 1.0

RPage {
    id:  viewer
    anchors.fill: parent

    property string fileName: "/home/user/MyDocs/Documents/Ebook/doupocangqiong.txt"
    //    property string fileName: "D:/alex/novol/jiudingji.txt"
    //    property string fileName: "D:/software/N950/Ebook/doupocangqiong.txt"
    //    property string fileName: "D:/software/N950/Ebook/yangshen.txt"
    property real lineSpace: 4
    property int fontSizeMin: 20
    property int fontSizeMax: 70
    property real lineHeight: fontSize + lineSpace
    property alias fontSize: viewerText.font.pixelSize
    property alias fontFamily: viewerText.font.family
    property alias color: viewerText.color
    property alias backgoundColor: pageContainer.color
    property alias smooth: viewerText.smooth
    property alias letterSpace: viewerText.font.letterSpacing
    property alias wordSpace: viewerText.font.wordSpacing
    property alias bold: viewerText.font.bold
    property alias underline: viewerText.font.underline
    property bool showToolBar: true
    property bool ignoreEmptyLine: false
    property bool autoPageTurning: false
    property bool showAutoPageTurningTime: true
    property int autoPageTurningTimeOut: 60
    property int autoPageTurningTimeCount: 0
    property int autoPageTurningTextFontSize: 30
    property color autoPageTurningTextFontColor: "black"
    property bool autoPageTurningPaused: false
    property bool nightMode:false
    property bool disableDisplayBlank:false

    property color configColor: "black"
    property color configTextColor: "white"
    property int configTextSize: 20

    property bool fileLoaded: false

    //Previous page's first char line number
    property int prevStartLineNumber: 0
    //Previous page's first char index in first line
    property int prevStartIndex: 0
    //Previous page's last char line number
    property int prevEndLineNumber: 0
    //Previous page's last char index in last line
    property int prevEndIndex: 0
    //Previous page's text
    property string prevText: ""

    //Current page's first char line number
    property int currentStartLineNumber: 0
    //Current page's first char index in first line
    property int currentStartIndex: 0
    //Current page's last char line number
    property int currentEndLineNumber: 0
    //Current page's last char index in last line
    property int currentEndIndex: 0
    //Current page's text
    property string currentText: ""

    //Next page's first char line number
    property int nextStartLineNumber: 0
    //Next page's first char index in first line
    property int nextStartIndex: 0
    //Next page's last char line number
    property int nextEndLineNumber: 0
    //Next page's last char index in last line
    property int nextEndIndex: 0
    //Next page's text
    property string nextText: ""

    //Prefetch length
    property int prefetchLenth: 500

    property Item valueSelectionDialogItem: null

    property Item colorSelectionDialogItem: null

    function confGridLen() {
        var minLen = Math.min(viewer.width, viewer.height)
        return (minLen - 20)/(confGrid.columns)
    }

    function hideConf() {
        confRect.visible = false
    }

    function toFixed(value, precision) {
        var number = new Number(value)
        return number.toFixed(precision)
    }

    function startTimer(restart, ignorePause) {
        console.log("startTimer:",
                    "restart:", restart,
                    "ignorePause:", ignorePause)
        if (viewer.fileLoaded &&
                viewer.autoPageTurning &&
                (ignorePause || !viewer.autoPageTurningPaused)) {
            if (restart) {
                viewer.autoPageTurningTimeCount = 0
            }
            timer.start()
        }
    }

    function stopTimer() {
        timer.stop()
    }

    function loadSettings() {
        viewer.fontSize = engine.setting(REngine.TextFontPixelSize)
        viewer.fontFamily = engine.setting(REngine.TextFontFamiliy)
        viewer.lineSpace = engine.setting(REngine.TextLineSpace)
        viewer.smooth = engine.setting(REngine.TextSmooth)
        viewer.wordSpace = engine.setting(REngine.TextFontWordSpacing)
        viewer.letterSpace = engine.setting(REngine.TextFontLetterSpacing)
        viewer.bold = engine.setting(REngine.TextFontBold)
        viewer.underline = engine.setting(REngine.TextFontUnderline)
        screen.allowedOrientations = engine.setting(REngine.Orientation)
        viewer.showToolBar = engine.setting(REngine.ShowToolbar)
        window.showToolBar = viewer.showToolBar
        viewer.color = engine.setting(REngine.TextColor)
        viewer.backgoundColor = engine.setting(REngine.TextBackgroud)
        viewer.autoPageTurning = engine.setting(REngine.AutoPageTurning)
        viewer.autoPageTurningTimeOut = engine.setting(REngine.AutoPageTurningTimeOut)
        viewer.showAutoPageTurningTime = engine.setting(REngine.ShowAutoPageTurningTime)
        viewer.nightMode = engine.setting(REngine.NightMode)
        viewer.disableDisplayBlank = engine.setting(REngine.DisableDisplayBlank)
        startTimer(false, false)
    }

    function openFileFinished(fileName, result) {
        console.debug("openFileFinished: fileName", fileName,
                      "result:", result)
        if (fileName === viewer.fileName) {
            showOpenFileIndicator(false)
            if (result === REngine.OpenFileSuccess ||
                    result === REngine.OpenFileSuccessWithDefaultCodec) {
                fileLoaded = true
                viewer.currentStartLineNumber = engine.lastLineNumber(viewer.fileName)
                viewer.currentStartIndex = engine.lastCharIndex(viewer.fileName)
                JS.getCurrentPage()
                viewerText.text = viewer.currentText
                pb1.value = engine.lineNumberToPercent(viewer.fileName, viewer.currentStartLineNumber)*100
                JS.saveCurrentPosition()
                if (result === REngine.OpenFileSuccessWithDefaultCodec) {
                    openFileWithDefaultCodec.fileName = viewer.fileName
                    openFileWithDefaultCodec.open()
                }
                startTimer(true, false)
            }
            else {
                fileLoaded = false
                openFileError.fileName = viewer.fileName
                openFileError.open()
            }
        }
        else {
            console.log("fileName is not the same, current:", viewer.fileName)
        }
    }

    function showOpenFileIndicator(show) {
        if (show) {
            openFileIndicator.running = true
            openFileIndicator.opacity = 1
        }
        else {
            openFileIndicator.running = false
            openFileIndicator.opacity = 0
        }
    }

    function handleViewModeVisibleChanged() {
        console.log("handleViewModeVisibleChanged: viewMode", platformWindow.viewMode,
                    "visible", platformWindow.visible)
        if (platformWindow.viewMode == WindowState.Fullsize && platformWindow.visible) {
            //visible, start timer
            startTimer(false, false)
        }
        else {
            //not visible, stop auto page turning
            stopTimer()
        }
    }
    Keys.onPressed: {
        console.log("Key pressed:", event.key)
        if (event.key == Qt.Key_VolumeUp) {
            console.log("VolumeUp, goto prev page")
            JS.switchToPrevPage()
            event.accepted = true
        }
        else if (event.key == Qt.Key_VolumeDown) {
            console.log("VolumeDown, goto next page")
            JS.switchToNextPage()
            event.accepted = true
        }
        else if (event.key == Qt.Key_VolumeMute) {
            console.log("VolumeMute, stop timer")
            stopTimer()
            event.accepted = true
        }
    }

    Connections {
        target: platformWindow
        onViewModeChanged: {
            console.log("viewModeChanged", platformWindow.viewMode)
            handleViewModeVisibleChanged()
            COM.handleViewModeVisibleChanged()
        }
        onVisibleChanged: {
            console.log("visibleChanged", platformWindow.visible)
            handleViewModeVisibleChanged()
            COM.handleViewModeVisibleChanged()
        }
    }

    Rectangle {
        id: confRect
        z: 1
        visible: false
        width: confGrid.width
        height: confGrid.height
        anchors.centerIn: parent
        color: "white"
        Grid {
            id: confGrid
            anchors.centerIn: parent
            columns: 3
            spacing: 2

            //Font size
            Rectangle {
                id: fontSizeConf
                width: confGridLen()
                height: width
                color: viewer.configColor
                Text {
                    id: fontSizeConfText
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Font Size")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        valueSelectionDialog.titleStr = fontSizeConfText.text
                        valueSelectionDialog.minimumValue = viewer.fontSizeMin
                        valueSelectionDialog.maximumValue = viewer.fontSizeMax
                        valueSelectionDialog.precision = 0
                        valueSelectionDialog.value = viewer.fontSize
                        valueSelectionDialog.stepSize =  1
                        valueSelectionDialog.inputMethodHints = Qt.ImhDigitsOnly
                        viewer.valueSelectionDialogItem = fontSizeConf
                        valueSelectionDialog.open()
                        hideConf()
                    }
                }
            }

//            //Word Space
//            Rectangle {
//                id: wordSpaceConf
//                width: confGridLen();
//                height: width
//                color: viewer.configColor
//                Text {
//                    id: wordSpaceConfText
//                    anchors.centerIn: parent
//                    color: viewer.configTextColor
//                    font.pixelSize: viewer.configTextSize
//                    text: qsTr("Word Space")
//                }
//                MouseArea {
//                    anchors.fill: parent
//                    onClicked: {
//                        valueSelectionDialog.titleStr = wordSpaceConfText.text
//                        valueSelectionDialog.minimumValue = 0
//                        valueSelectionDialog.maximumValue = 20
//                        valueSelectionDialog.precision = 0
//                        valueSelectionDialog.value = viewer.wordSpace
//                        valueSelectionDialog.stepSize =  1
//                        valueSelectionDialog.inputMethodHints = Qt.ImhDigitsOnly
//                        viewer.valueSelectionDialogItem = wordSpaceConf
//                        valueSelectionDialog.open()
//                        hideConf()
//                    }
//                }
//            }

            //Letter space
//            Rectangle {
//                id: letterSpaceConf
//                width: confGridLen();
//                height: width
//                color: viewer.configColor
//                Text {
//                    id: letterSpaceConfText
//                    anchors.centerIn: parent
//                    color: viewer.configTextColor
//                    font.pixelSize: viewer.configTextSize
//                    text: qsTr("Letter Space")
//                }
//                MouseArea {
//                    anchors.fill: parent
//                    onClicked: {
//                        valueSelectionDialog.titleStr = letterSpaceConfText.text
//                        valueSelectionDialog.minimumValue = 0
//                        valueSelectionDialog.maximumValue = 20
//                        valueSelectionDialog.precision = 0
//                        valueSelectionDialog.value = viewer.letterSpace
//                        valueSelectionDialog.stepSize =  1
//                        valueSelectionDialog.inputMethodHints = Qt.ImhDigitsOnly
//                        viewer.valueSelectionDialogItem = letterSpaceConf
//                        valueSelectionDialog.open()
//                        hideConf()
//                    }
//                }
//            }

            //Line space
            Rectangle {
                id: lineSpaceConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    id: lineSpaceConfText
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Line Space")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        valueSelectionDialog.titleStr = lineSpaceConfText.text
                        valueSelectionDialog.minimumValue = 0
                        valueSelectionDialog.maximumValue = 20
                        valueSelectionDialog.precision = 0
                        valueSelectionDialog.value = viewer.lineSpace
                        valueSelectionDialog.stepSize =  1
                        valueSelectionDialog.inputMethodHints = Qt.ImhDigitsOnly
                        viewer.valueSelectionDialogItem = lineSpaceConf
                        valueSelectionDialog.open()
                        hideConf()
                    }
                }
            }

            //Background
            Rectangle {
                id: backgroundConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Background")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        viewer.colorSelectionDialogItem = backgroundConf
                        colorSelectionDialog.open()
                    }
                }
            }

            //Font color
            Rectangle {
                id: fontColorConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Font Color")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        viewer.colorSelectionDialogItem = fontColorConf
                        colorSelectionDialog.open()
                    }
                }
            }

            //Night Mode
            Rectangle {
                id: nightModeConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: viewer.nightMode === true ? qsTr("Day Mode") : qsTr("Night Mode")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        viewer.nightMode = !viewer.nightMode
                        JS.saveNightMode()
                        //night mode affects the font color and background color
                        //so need to load settings
                        loadSettings()
                    }
                }
            }

            //Auto page turning
            Rectangle {
                id: pageTurningConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: viewer.autoPageTurning === true ? qsTr("Paging Off") : qsTr("Paging On")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        viewer.autoPageTurning = !viewer.autoPageTurning
                        if (viewer.autoPageTurning) {
                            startTimer(true, false)
                        }
                        else {
                            stopTimer()
                        }

                        JS.saveAutoPageTurning()
                        //Auto page turning affects available size and timer
                        //So need to load settings
                        loadSettings()
                        JS.reloadCurrentPage()
                    }
                }
            }

//            //Bold
//            Rectangle {
//                id: boldConf
//                width: confGridLen();
//                height: width
//                color: viewer.configColor
//                Text {
//                    anchors.centerIn: parent
//                    color: viewer.configTextColor
//                    font.pixelSize: viewer.configTextSize
//                    text: qsTr("Bold")
//                }
//                MouseArea {
//                    anchors.fill: parent
//                    onClicked: {
//                        hideConf()
//                        viewer.bold = !viewer.bold
//                        JS.reloadCurrentPage()
//                        JS.saveBold()
//                    }
//                }
//            }

            //Chapter
            Rectangle {
                id: chapterConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Chapter")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        viewer.pageStack.push(Qt.resolvedUrl("ChapterView.qml"),
                                              {window: viewer.window,
                                                  fileName: viewer.fileName})
                    }
                }
            }

            //Orientation
            Rectangle {
                id: orientationConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: qsTr("Orientation")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        hideConf()
                        orientationMenu.open()
                    }
                }
            }

            //Toolbar
            Rectangle {
                id: showToolBarConf
                width: confGridLen();
                height: width
                color: viewer.configColor
                Text {
                    anchors.centerIn: parent
                    color: viewer.configTextColor
                    font.pixelSize: viewer.configTextSize
                    text: viewer.showToolBar === true ? qsTr("Hide ToolBar") : qsTr("Show ToolBar")
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        //Only handle when show quick setting is on, or there is no way back to previous view
                        if (engine.setting(REngine.ShowQuickSetting)) {
                            hideConf()
                            viewer.showToolBar = !viewer.showToolBar
                            JS.reloadCurrentPage()
                            JS.saveShowToolBar()
                        }
                        else {
                            infoBanner.text = qsTr("Can't hide toolbar when \"Show Quick Setting\" is disabled")
                            infoBanner.show()
                        }
                    }
                }
            }
        }
    }

    onHeightChanged: {
        console.log("height changed", height)
        //only reload when status is active
        if (status == PageStatus.Active) {
            JS.reloadCurrentPage()
        }
    }

    //    onShowToolBarChanged: {
    //        console.log("ShowToolBar changed, reload")
    //        JS.reloadCurrentPage()
    //    }

    Connections{
        target: screen
        onCurrentOrientationChanged: {
            console.log("CurrentOrientation changed, reload")
            JS.reloadCurrentPage()
        }
    }

    onStatusChanged: {
        //reload current settings
        if (status == PageStatus.Active) {
//            COM.disableDisplayBlank(true)
            loadSettings()
            COM.disableDisplayBlank(viewer.disableDisplayBlank)
            JS.reloadCurrentPage()
        }
        else if (status == PageStatus.Activating) {
            screen.allowedOrientations = engine.setting(REngine.Orientation)
        }
        else if (status == PageStatus.Deactivating) {
            COM.disableDisplayBlank(false)
            stopTimer()
        }
    }

    onCurrentStartLineNumberChanged: {
        pb1.value = engine.lineNumberToPercent(viewer.fileName, viewer.currentStartLineNumber)*100
    }

    Rectangle {
        id: pageContainer
        anchors.fill: parent
        color: "transparent"
        PinchArea {
            id: pichArea
            anchors.fill: parent
            pinch.target: pageContainer
            pinch.maximumScale: Math.ceil(viewer.fontSizeMax/viewer.fontSize)
            pinch.minimumScale: viewer.fontSizeMin/viewer.fontSize
            onPinchFinished: {
                console.log("pinch updated: ",
                            "pinch.scale", pinch.scale,
                            "target.scale", pichArea.pinch.target.scale)
                var size = Math.floor(pichArea.pinch.target.scale*viewer.fontSize)
                if (size < viewer.fontSizeMin) {
                    size = viewer.fontSizeMin
                }

                if (size > viewer.fontSizeMax) {
                    size = viewer.fontSizeMax
                }
                viewer.fontSize = size

                pichArea.pinch.target.scale = 1
                JS.reloadCurrentPage()
                JS.saveFontSize()
            }
        }

        MouseArea {
            id: mouseA
            anchors.fill: parent
            onClicked: {
                console.log("clicked:", mouseX, mouseY)
                if (confRect.visible) {
                    confRect.visible = !confRect.visible
                }
                else {
                    if (mouseY <= parent.height/2) {
                        //Move to previous page
                        JS.switchToPrevPage()
                        startTimer(true, false)
                    }
                    else {
                        //Move to next page
                        JS.switchToNextPage()
                        startTimer(true, false)
                    }
                }
            }
            onPressAndHold: {
                if (engine.setting(REngine.ShowQuickSetting)) {
                    confRect.visible = !confRect.visible
                }
            }
    //        onDoubleClicked: {
    //            viewer.showToolBar = !viewer.showToolBar
    //            JS.reloadCurrentPage()
    //            JS.saveShowToolBar()
    //        }
        }

        RProgressBar {
            id: autoPageTurningPb
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            opacity: (viewer.autoPageTurning && viewer.showAutoPageTurningTime)? 1 : 0
            height: (viewer.autoPageTurning && viewer.showAutoPageTurningTime)? 36 : 0
            minValue: 0
            maxValue: viewer.autoPageTurningTimeOut-1
            value: 0
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    if (viewer.autoPageTurningPaused == false) {
                        stopTimer()
                        viewer.autoPageTurningPaused = true
                    }
                    else {
                        startTimer(false, true)
                        viewer.autoPageTurningPaused = false
                    }
                }
            }
            Text {
                anchors.centerIn: parent
                text: qsTr("Paused")
                font.pixelSize: autoPageTurningPb.height-2
                color: "black"
                visible: !timer.running
            }
        }

        Timer {
            id: timer
            interval: 1000 //1 second
            repeat: true
//            running: viewer.autoPageTurning
            onTriggered: {
                viewer.autoPageTurningTimeCount += 1
                var mod = viewer.autoPageTurningTimeCount%viewer.autoPageTurningTimeOut
                autoPageTurningPb.value = mod
                if (mod == 0) {
                    JS.switchToNextPage()
                }
                console.log("timer triggered, viewer.autoPageTurningTimeCount:", viewer.autoPageTurningTimeCount,
                            "mod", mod,
                            "autoPageTurningPb.value", autoPageTurningPb.value)
            }
        }

        Text {
            id: viewerText
            clip: true
            smooth: true
            anchors.top: parent.top
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: autoPageTurningPb.top
            lineHeight: viewer.lineHeight
            wrapMode: Text.Wrap
            lineHeightMode: Text.FixedHeight
        }

//        Item {
//            id: pageTurningTimer
//            width: 40
//            height: 40
//            anchors.bottom: parent.bottom
//            anchors.right: parent.right
//            visible: viewer.autoPageTurning && viewer.showAutoPageTurningTime
//            MouseArea {
//                anchors.fill: parent
//                onClicked: {

//                }
//            }

//            Timer {
//                id: timer
//                interval: 1000 //1 second
//                repeat: true
//                running: viewer.autoPageTurning
//                onTriggered: {
//                    viewer.autoPageTurningTimeCount += 1
//                    var mod = viewer.autoPageTurningTimeCount%viewer.autoPageTurningTimeOut
//                    pageTurningTimerText.text = viewer.autoPageTurningTimeOut - mod
//                    if (mod == 0) {
//                        JS.switchToNextPage()
//                    }
//                    console.log("timer triggered, viewer.autoPageTurningTimeCount:", viewer.autoPageTurningTimeCount,
//                                "mod", mod,
//                                "pageTurningTimerText.text", pageTurningTimerText.text)
//                }
//            }

//            Text {
//                id: pageTurningTimerText
//                anchors.fill: parent
//                font.pixelSize: viewer.autoPageTurningTextFontSize
//                color: viewer.autoPageTurningTextFontColor
//            }
//        }
    }

    BusyIndicator {
        id: openFileIndicator
        anchors.centerIn: parent
        platformStyle: BusyIndicatorStyle { size: "large" }
    }

    QueryDialog {
        id: openFileError
        property string fileName: ""
        acceptButtonText: qsTr("OK")
        message: qsTr("Could not open file:")+ fileName+qsTr(" \nPlease check the file is exist and accessible.")
        titleText: qsTr("Open File Failed")
    }

    QueryDialog {
        id: openFileWithDefaultCodec
        property string fileName: ""
        acceptButtonText: qsTr("OK")
        message: qsTr("Could not determine text encoding codec, use default codec to decoding.")+qsTr(" \nPlease change the codec mannually if it's not correct.")
        titleText: qsTr("Open File Success")
    }

    Component.onCompleted: {
        console.log("page loaded: width, height, fileName",
                    width, height, fileName)
        loadSettings()
        showOpenFileIndicator(true)
        engine.asyncOpenFile(fileName)
    }
    Connections {
        target: engine
        onFileOpened: openFileFinished(fileName, result)
    }

    tools: ToolBarLayout {
        ToolIcon {
            id: backTool
            iconId: "toolbar-back"
            onClicked: {
                console.log("Back button clicked")
                viewer.pageStack.pop(recentPage)
            }
        }

        Progress {
            id: pb1
            anchors.left: backTool.right
            anchors.right: menuTool.left
            height: parent.height
            minimumValue: 0
            maximumValue: 100
            value: 0
            onClicked: {
                valueSelectionDialog.titleStr = qsTr("Jump to")
                valueSelectionDialog.minimumValue = 0
                valueSelectionDialog.maximumValue = 100
                valueSelectionDialog.precision = 2
                valueSelectionDialog.value = engine.lineNumberToPercent(viewer.fileName, viewer.currentStartLineNumber)*100
                valueSelectionDialog.stepSize =  0.01
                valueSelectionDialog.inputMethodHints = Qt.ImhFormattedNumbersOnly
                viewer.valueSelectionDialogItem = pb1
                valueSelectionDialog.open()
            }
        }

        ToolIcon {
            id: menuTool
            iconId: "toolbar-view-menu"
            onClicked: {
                console.log("optionsMenu clicked")
                optionsMenu.open()
            }
        }
    }

    TextEditDialog {
        id: bookmarkEditDialog
        titleText: qsTr("Save Bookmark")
        onAccepted: {
            var saveNote = ""
            if (bookmarkEditDialog.note != null) {
                saveNote = bookmarkEditDialog.note
            }

            engine.saveBookmark(viewer.fileName, viewer.currentStartLineNumber,
                                viewer.currentStartIndex, saveNote)
        }
    }

    InfoBanner {
        id: infoBanner
    }

    ContextMenu {
        id: optionsMenu
        MenuLayout {
            MenuItem {
                text: qsTr("Add Bookmark")
                onClicked: {
                    bookmarkEditDialog.open()
                }
            }
            MenuItem {
                text: qsTr("View Bookmarks")
                onClicked: {
                    viewer.pageStack.push(Qt.resolvedUrl("BookmarkView.qml"),
                                          {window: viewer.window,
                                              fileName: viewer.fileName})
                }
            }
            MenuItem {
                visible: engine.showChapterMenu()
                text: qsTr("View Chapter Menu")
                onClicked: {
                    viewer.pageStack.push(Qt.resolvedUrl("ChapterView.qml"),
                                          {window: viewer.window,
                                              fileName: viewer.fileName})
                }
            }
            MenuItem {
                text: qsTr("Copy Screen to Clipboard")
                onClicked: {
                    engine.copyToClipboard(viewerText.text)
                    infoBanner.text = qsTr("Text copied to clipboard")
                    infoBanner.show()
                }
            }
            MenuItem {
                text: qsTr("Quick Setting")
                onClicked: {
                    confRect.visible = true
                }
            }
            MenuItem {
                text: qsTr("Setting")
                onClicked: {
                    viewer.pageStack.push(Qt.resolvedUrl("SettingView.qml"),
                                          {  window: viewer.window,
                                              orientationLock: viewer.orientationLock,
                                              currentFile: viewer.fileName })
                }
            }
            MenuItem {
                text: qsTr("Help")
                onClicked: {
                    help.open()
                }
            }
//            MenuItem {
//                text: qsTr("About")
//                onClicked: {
//                    about.open()
//                }
//            }
        }
    }

    About {
        id: about
    }

    Help {
        id: help
    }

    ContextMenu {
        id: orientationMenu
        MenuLayout {
            id: orientationMenuLayout
            MenuItem {
                text: qsTr("Auto")
                onClicked: {
                    screen.allowedOrientations = Screen.All
                    JS.saveOrientation()
                }
            }
            MenuItem {
                text: qsTr("Portrait")
                onClicked: {
                    screen.allowedOrientations = Screen.Portrait
                    JS.saveOrientation()
                }
            }
            MenuItem {
                text: qsTr("Landscape")
                onClicked: {
                    screen.allowedOrientations = Screen.Landscape
                    JS.saveOrientation()
                }
            }
            MenuItem {
                text: qsTr("Portrait Inverted")
                onClicked: {
                    screen.allowedOrientations = Screen.PortraitInverted
                    JS.saveOrientation()
                }
            }
            MenuItem {
                text: qsTr("Landscape Inverted")
                onClicked: {
                    screen.allowedOrientations = Screen.LandscapeInverted
                    JS.saveOrientation()
                }
            }
            MenuItem {
                text: qsTr("Current")
                onClicked: {
                    screen.allowedOrientations = screen.currentOrientation
                    JS.saveOrientation()
                }
            }
        }
    }

    RValueSelectionDialog {
        id: valueSelectionDialog
        onAccepted: {
            console.log("valueSelectDialog accepted, value", valueSelectionDialog.value)
            if (viewer.valueSelectionDialogItem == lineSpaceConf) {
                viewer.lineSpace = valueSelectionDialog.value
                JS.saveLineSpace()
                JS.reloadCurrentPage()
            }
//            else if (viewer.valueSelectionDialogItem == wordSpaceConf) {
//                viewer.wordSpace = valueSelectionDialog.value
//                JS.saveWordSpace()
//                JS.reloadCurrentPage()
//            }
            else if (viewer.valueSelectionDialogItem == fontSizeConf) {
                viewer.fontSize = valueSelectionDialog.value
                JS.saveFontSize()
                JS.reloadCurrentPage()
            }
//            else if (viewer.valueSelectionDialogItem == letterSpaceConf) {
//                viewer.letterSpace = valueSelectionDialog.value
//                JS.saveLetterSpace()
//                JS.reloadCurrentPage()
//            }
            else if (viewer.valueSelectionDialogItem == pb1) {
                viewer.currentStartLineNumber = engine.lineNumberOfPercent(viewer.fileName, valueSelectionDialog.value/100)
                viewer.currentStartIndex = 0;
                console.log("Jump to ", valueSelectionDialog.value,"%", "lineNumber", viewer.currentStartLineNumber)
                JS.saveCurrentPosition()
                JS.reloadCurrentPage()
            }
        }
    }

    ColorSelectionDialog {
        id: colorSelectionDialog
        onAccepted: {
            console.log("colorSelectionDialog accepted, color", colorSelectionDialog.model.get(selectedIndex).name)
            if (viewer.colorSelectionDialogItem == backgroundConf) {
                viewer.backgoundColor = colorSelectionDialog.model.get(selectedIndex).name
                JS.saveBackgoundColor()
            }
            else if (viewer.colorSelectionDialogItem == fontColorConf) {
                viewer.color = colorSelectionDialog.model.get(selectedIndex).name
                JS.saveColor()
            }
        }
    }
}
